﻿using UnityEngine;
/// <summary>
/// 绑定模拟MonoBehaviour
/// </summary>
public abstract class AbsBindSimulateBehaviour_Mono : MonoBehaviour, IBindSimulateBehaviour
{
    /// <summary>
    /// 绑定的ISimulateBehaviour对象
    /// </summary>
    [SerializeField]
    UnityDictionary<long, ISimulateBehaviour> mBindISB;
    /// <summary>
    /// 绑定事件Key
    /// </summary>
    public abstract int bindEvtKey { get; }
    /// <summary>
    /// 绑定的ISimulateBehaviour对象
    /// </summary>
    public UnityDictionary<long, ISimulateBehaviour> bindISB { get { return mBindISB; } }
    /// <summary>
    /// 绑定的ISimulateBehaviour对象
    /// </summary>
    /// <param name="_bindISB">绑定的ISimulateBehaviour对象</param>
    public void BindSimulateBehaviour(ISimulateBehaviour _bindISB)
    {
        if (mBindISB == null)
        {
            mBindISB = new UnityDictionary<long, ISimulateBehaviour>();
        }
        if (!mBindISB.ContainsKey(_bindISB.simulateGlobalId))
        {
            mBindISB[_bindISB.simulateGlobalId] =_bindISB;
        }
#if UNITY_EDITOR
        else
        {
            Debug.LogError($"BindSimulateBehaviour=>same simulateGlobalId【{_bindISB.simulateGlobalId}】");
        }
#endif
        OnAfterBindSimulateBehaviour(_bindISB);
    }
    /// <summary>
    /// 绑定ISimulateBehaviour对象之后
    /// </summary>
    /// <param name="_bindISB">绑定的ISimulateBehaviour对象</param>
    protected virtual void OnAfterBindSimulateBehaviour(ISimulateBehaviour _bindISB) { }

    /// <summary>
    /// 移除绑定的ISimulateBehaviour对象
    /// </summary>
    /// <param name="_bindISB">绑定的ISimulateBehaviour对象</param>
    /// <returns>GameObject.InstanceID</returns>
    public int RemoveBindEventBehaviour(ISimulateBehaviour _bindISB)
    {
        int result = gameObject.GetInstanceID();
        if (mBindISB != null)
        {
            mBindISB.Remove(_bindISB.simulateGlobalId);
            OnRemoveBindEventBehaviour(_bindISB);
        }
        return result;
    }

    /// <summary>
    /// 移除绑定的ISimulateBehaviour对象
    /// </summary>
    /// <param name="_bindISB">绑定的ISimulateBehaviour对象</param>    
    protected virtual void OnRemoveBindEventBehaviour(ISimulateBehaviour _bindISB) { }

    /// <summary>
    /// 销毁
    /// </summary>
    private void OnDestroy()
    {
        mBindISB.Clear();
    }
}